<template>
  <div class="gl_contentBox gl_heightFull">
    <!-- 搜索 -->
    <div class="gl_searchBox gl_mb_15">
      <el-row :gutter="20">
        <el-col :md="6" :lg="4">
          <p>课程名称</p>
          <el-input v-model="searchForm.CourseName" placeholder="请输入课程名称" size="mini" clearable @change="getData()" />
        </el-col>
        <el-col :md="6" :lg="4">
          <p>授课模式</p>
          <el-select v-model="searchForm.TeachingModeCode" size="mini" placeholder="请选择授课模式" @change="getData()">
            <el-option label="全部" value="" />
            <el-option v-for="item in dict.teachingMode" :key="item.code" :label="item.value" :value="item.code" />
          </el-select>
        </el-col>
        <el-col v-if="!isOrderPage" :md="6" :lg="4">
          <p>教练姓名</p>
          <el-input v-model="searchForm.CoachName" placeholder="请输入教练姓名" size="mini" clearable @change="getData()" />
        </el-col>
        <el-col v-if="showType === 'list'" :md="7" :lg="5">
          <p>上课时间</p>
          <el-date-picker
            v-model="classTime"
            type="daterange"
            range-separator="至"
            start-placeholder="请选择日期"
            end-placeholder="请选择日期"
            size="mini"
            value-format="yyyy-MM-dd"
            style="width:100%"
            @change="timeChange"
          />
        </el-col>
        <el-col :md="9" :lg="7">
          <el-button style="margin-top:27px" type="primary" size="mini" @click="getData()">筛选</el-button>
          <el-button style="margin-top:27px" type="warning" size="mini" @click="reset()">重置</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 操作 -->
    <el-row v-if="!isOrderPage" type="flex" justify="space-between" class="gl_mb_15">
      <el-col :span="14">
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="createClass()">排课</el-button>
        <el-button type="success" :loading="downloadLoading" icon="el-icon-download" size="mini" @click="exportClass()">导出课表</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="downloadPdf('#pdfDom')">下载课表PDF</el-button>
      </el-col>
      <el-col :span="12" class="change_icon" align="right">
        <template v-if="showType === 'list'">
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content">方格</div>
            <i class="el-icon-menu icon_change" @click="changeView('view')" />
          </el-tooltip>
        </template>
        <template v-if="showType === 'view'">
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content">列表</div>
            <i class="el-icon-s-operation icon_change" @click="changeView('list')" />
          </el-tooltip>
        </template>
      </el-col>
    </el-row>
    <div id="pdfDom">
      <!-- 列表样式 -->
      <template v-if="showType === 'list'">
        <el-table v-loading="loading" class="gl_table_noBorder" :data="tableData" size="mini">
          <el-table-column type="index" label="序号" :width="50" align="center" />
          <el-table-column prop="className" label="班级名称" :min-width="180" />
          <el-table-column prop="courseTeachingMode.name" label="授课模式" :width="140" align="center" />
          <el-table-column prop="courseName" label="上课课程" :min-width="180" />
          <el-table-column prop="courseEmployees" label="教练" :min-width="160">
            <template slot-scope="{row}">
              <div v-for="coach in row.courseEmployees" :key="coach.id">
                <div v-if="coach.courseEmployeeTypeCode == 'Coach'">
                  {{ coach.employee && coach.employee.name }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="courseDate" label="上课时间" :width="200">
            <template slot-scope="{row}">
              <span v-if="!row.courseDate || row.courseDate == '0001-01-01T00:00:00'">- -</span>
              <span v-else>{{ row.courseDate | FormatDate('yyyy-MM-dd') }}</span>
              <span class="gl_pl_5">{{ 10 > row.startHour ? '0' + row.startHour : row.startHour }}:{{ 10 > row.startMinute ? '0' + row.startMinute : row.startMinute }} - {{ 10> row.endHour ? '0' + row.endHour : row.endHour }}:{{ 10 > row.endMinute ? '0' + row.endMinute : row.endMinute }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" :width="180">
            <template slot-scope="{row}">
              <el-button size="mini" type="text" @click="changeRoute(row, 'SignList')">签到</el-button>
              <el-button size="mini" type="text" @click="changeRoute(row, 'ArrangingList')">详情</el-button>
              <el-button size="mini" type="text" @click="edit(row)">编辑</el-button>
              <el-button size="mini" type="text" @click="remove(row)">
                <span class="gl_color_error">删除</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="gl_pt_15" style="text-align: right;">
          <el-pagination
            :current-page="form.Page"
            :page-size="form.MaxResultCount"
            :total="totalPage"
            layout="total,sizes,prev,pager,next,jumper"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="sizeChange"
            @current-change="pageIndexChange"
          />
        </el-row>
        <CreateDialog ref="createDialog" @refresh="refresh" />
      </template>
      <!-- 方块样式 -->
      <template v-if="showType === 'view'">
        <Day
          v-if="typeTimeTable == 'day'"
          :type-time-table="typeTimeTable"
          :search-form="searchForm"
          @changeType="changeType"
          @getTime="getTime"
        />
        <Week
          v-if="typeTimeTable == 'week'"
          :type-time-table="typeTimeTable"
          :search-form="searchForm"
          @changeType="changeType"
          @getTime="getTime"
        />
        <Month
          v-if="typeTimeTable == 'month'"
          :type-time-table="typeTimeTable"
          :search-form="searchForm"
          @changeType="changeType"
          @getTime="getTime"
        />
      </template>
    </div>
  </div>
</template>

<script>
import Day from './timetableType/day';
import Week from './timetableType/week';
import Month from './timetableType/month';
import CreateDialog from '@/components/Class/createDialog.vue';
import { mapState, mapActions } from 'vuex';
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText, getPdf } from '@/lib';
import {
  api_GET_ClubCourseSchedule, // 获取课表
  api_DELETE_ClubCourseScheduleId // 删除
} from '@/extend/api/hallswaggerApi/app.js';
import {
  Api_GET_ClubCourseScheduleQO
} from '@/lib/form/hall/swaggerForm.js';
export default {
  name: 'Timetable',
  components: {
    Day,
    Week,
    Month,
    CreateDialog
  },
  data() {
    return {
      loading: false,
      downloadLoading: false,
      showType: 'view',
      pdfName: '课表PDF',
      searchForm: {
        CourseName: null,
        TeachingModeCode: null,
        CoachName: null
      },
      totalPage: 0,
      form: new Api_GET_ClubCourseScheduleQO(),
      isOrderPage: false, // 是否是预约管理页面
      classTime: [], // 上课时间
      typeTimeTable: 'week', // 课表类型，日、周、月
      time: '',
      tableData: []
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  created() {
    this.getDict();
    if (this.searchForm) {
      this.searchForm.TeachingModeCode = '';
    }
    if (this.$route.path.indexOf('/selectAppointmentClass') > 0) {
      this.isOrderPage = true;
    }
    if (this.$route.path.indexOf('/trialclass') > 0) {
      this.isOrderPage = true;
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    downloadPdf(id) {
      getPdf(id, this.pdfName);
    },
    // 获取数据
    getData(id, page) {
      if (this.showType === 'list') {
        var that = this;
        that.loading = true;
        that.form.Page = page || 1;
        that.form.SkipCount = (that.form.Page - 1) * that.form.MaxResultCount;
        that.form.CourseName = that.searchForm.CourseName;
        that.form.TeachingModeCode = that.searchForm.TeachingModeCode;
        that.form.CoachName = that.searchForm.CoachName;
        that.form.IsFinished = null;
        that.form.IncludeClass = true;
        that.form.IncludeCourse = true;
        that.form.IncludeCoach = true;
        that.form.IncludeClassroom = true;
        that.form.IncludeMessageTemplate = true;
        that.form.IncludeDeleted = true;
        that.form.ClassId = id || null;
        api_GET_ClubCourseSchedule(that.form).then(res => {
          that.tableData = res.items;
          that.totalPage = res.totalCount;
          that.loading = false;
        }).catch(error => {
          that.loading = false;
          that.$message({ type: 'error', message: error.error.message });
        });
      }
    },
    // 上课时间选择器
    timeChange(val) {
      if (val instanceof Array) {
        this.form.StartTime = this.classTime[0];
        this.form.EndTime = this.classTime[1];
      } else {
        this.form.StartTime = '';
        this.form.EndTime = '';
      }
      this.getData('', this.form.Page);
    },
    // 切换赛事课表的形式 list / view
    changeView(type) {
      this.showType = type;
      if (this.showType === 'list') {
        this.getData();
      }
    },
    // 排课
    createClass() {
      this.$router.push({
        name: 'CreateClass'
      });
    },
    // 切换日、周、月
    changeType(code) {
      this.typeTimeTable = code;
    },
    // 签到 or 详情
    changeRoute(data, code) {
      const query = {
        name: code,
        id: data.classId
      };
      this.$router.push({
        name: 'ArrangingTypeList',
        query: query
      });
    },
    // 编辑
    edit(data) {
      this.$refs.createDialog.open('编辑', data);
    },
    refresh() {
      this.getData('', this.form.Page);
    },
    // 删除
    remove(data) {
      var that = this;
      that.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api_DELETE_ClubCourseScheduleId(data.id).then(res => {
          that.getData('', that.form.Page);
          that.$message({ type: 'success', message: '删除成功!' });
        }).catch(error => {
          that.$message({ type: 'error', message: '删除失败 ' + error.error.message });
        });
      }).catch(() => {});
    },
    // 重置搜索表单
    reset() {
      this.form = new Api_GET_ClubCourseScheduleQO();
      this.classTime = [];
      this.searchForm = {
        CourseName: null,
        TeachingModeCode: null,
        CoachName: null
      };
      this.searchForm.TeachingModeCode = '';
      this.getData();
    },
    getTime(val) {
      this.time = val;
    },
    // 导出课表
    exportClass() {
      var that = this;
      that.downloadLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '课表' + '.xlsx';
      const form = JSON.parse(JSON.stringify(that.form));
      if (that.showType === 'view') {
        form.StartTime = that.time ? that.time.split('~')[0] : null;
        form.EndTime = that.time ? that.time.split('~')[1] : null;
      }
      delete form.SkipCount;
      delete form.MaxResultCount;
      delete form.Page;
      const GetCourseScheduleInput = JSON.stringify(form);
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { reportName: 'CourseSchedule', GetCourseScheduleInput: GetCourseScheduleInput }, WEB_CONFIG.VUE_APP_SWAGGER_HALL_BASE).then(res => {
        that.downloadLoading = false;
      }).catch(error => {
        that.downloadLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    sizeChange(MaxResultCount) {
      this.form.MaxResultCount = MaxResultCount;
      this.getData();
    },
    pageIndexChange(currentPage) {
      this.getData('', currentPage);
    }
  }
};
</script>

<style scoped>
.change_icon {
  height: 28px;
  line-height: 32px;
}
.change_icon .icon_change {
  font-size: 18px;
  width: 24px;
  height: 24px;
  visibility: visible;
  color: #696b6c;
  cursor: pointer;
}
.change_icon .icon_change:hover {
  color: #1890ff;
}
</style>
